﻿/* $RCSFile: ShowPrivateDocument.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.EMailing/PageModules/DownloadSession/ShowPrivateDocument.ascx.cs $
 * $log$
 * Revision 23 2010/08/09 11:12:45  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 10 2010/08/09 10:13:18  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Web.Security;
using System.Xml;
using System.Configuration;

using AddonNice;
using AddonNice.Authentication;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using AddonNice.CRMEMailing;
using AddonNice.Settings.CRMEMailing;
using AddonNice.CRMEMailing.Settings.UI.WebControls;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.DownloadSession
{
 	#region Local TraceSwitch 
	
    public class ShowPrivateDocumentTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	            =	new ADNTraceSwitch("ShowPrivateDocumentTrace","Special Trace Switch for ShowPrivateDocumentTrace");
	}
	
    #endregion Local TraceSwitch 

    /// <summary>
    /// Initializer class for ShowPrivateDocument 
    /// </summary>
    public class ShowPrivateDocumentSI : PortalCRMModuleControlSI
    {
        public ShowPrivateDocumentSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ShowPrivateDocumentSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ShowPrivateDocumentSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ShowPrivateDocumentSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ShowPrivateDocumentSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    /// <summary>
    ///  Nomaly used in an Iframe for the custom entity privateDocument
    ///  Simply display the title of document, its name and allows clicking on the name to display content
    /// </summary>
    public partial class ShowPrivateDocument : PortalEmailingModule
    {
        XrmEMailingDB dwnDB               =   new XrmEMailingDB();

		#region Global Implementation

        public override Guid GuidID 
		{
			get
			{
				return new Guid(AStr.ShowPrivateDocumentGuid);
			}
		}

		#endregion Global Implementation
        
        #region Ctor

        /// <summary>
		/// Ctor Set the properties of the module
		/// </summary>
        public ShowPrivateDocument()
        {
            if (ShowPrivateDocumentTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ShowPrivateDocument Ctor enter at: {0}", DateTime.UtcNow), ShowPrivateDocumentTrace.Sw.Info);
        }

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new ShowPrivateDocumentSI(bSettings,this);
        }

        #endregion Ctor

        protected void Page_Load(object sender, EventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ShowPrivateDocument Page_Load BEG IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
            if ( ! IsPostBack )
            {
                if ( !IsUnderCRM )
                {
		            if ( ShowPrivateDocumentTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ShowPrivateDocument Page_Load module not installed with its settings ModuleID: {0}, Title: {1}.",ModuleID,TitleText),ShowPrivateDocumentTrace.Sw.Info);
                    Literal3.Visible                    =   false;
                    LblFileName.Visible                 =   false;
                    ShowBtn.Visible                     =   false;
                    Label notInstalled                  =   new Label();
                    notInstalled.CssClass               =   "Error";
                    notInstalled.Text                   =   "This module must be called inside a CRM IFrame";
                    int idx                             =   Controls.IndexOf(LblFileName);
                    Controls.AddAt(idx,notInstalled);
                    LblFileName.Visible     =   false;

                    return;
                }
                SqlDataReader dr                        =   null;
                try
                {
                    bool found                          =   false;
                    if ( !IsInEntityCreationMode )
                    {
                        dr                              =   dwnDB.GetPrivateDocumentByEntityId(EntityID);
                        if ( dr.Read() )
                        {
                            int docId                   =   (int)dr[AStr.DBPrivateDocumentId];
                            string fileName             =   (string)dr[AStr.DBFilename];
                            DateTime    CreateDate      =   (DateTime)dr[AStr.DBCreatedDate];
                            DateTime    UpdateDate      =   (DateTime)dr[AStr.DBUpdateDate];
                            ShowBtn.OnClientClick       =   GetPopupCommand();
                            string url                  =   string.Format("{0}/DownloadSession/downloadgenerator.aspx?id={1}&crmid={2}&pageid={3}&Mid={4}",
                                            new object[] { Config.ModulesPath.Substring(1),docId,EntityID,PageID,ModuleID });
                            ShowBtn.Attributes.Add("href",url);
                            LblFileName.Text            =   fileName;
                            found                       =   true;
                            if ( ShowPrivateDocumentTrace.Sw.TraceVerbose )
                                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]ShowPrivateDocument Page_Load found docId: {0}, CreateDate: {1}, UpdateDate: {2}, url: {3}",
                                    new object[]{docId,CreateDate,UpdateDate,url}),ShowPrivateDocumentTrace.Sw.Info);
                        }
                    }
                    if ( !found )
                    {
                        Literal3.Visible                =   false;
                        LblFileName.Visible             =   false;
                        ShowBtn.Visible                 =   false;
                    }
                }
                catch(Exception ex)
                {
                    if (ShowPrivateDocumentTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ShowPrivateDocument Page_Load ex: {0}",ex),ShowPrivateDocumentTrace.Sw.Info);
                    throw;
                }
                finally
                {
                    if ( dr != null )
                        dr.Close();
                }
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]ShowPrivateDocument Page_Load END.",ModuleTraceSwitch.Sw.Info);
        }

        #region Std overrides 

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            //string strcult              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent()
		{
            Load                            +=  new EventHandler(Page_Load);
 		}

        #endregion
    }
}